package com.bracelet.util.netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * netty服务器，主要用于与客户端通讯
 */
@Component
@Slf4j
public class NettyServer implements CommandLineRunner {
    @Value("${tcp.server.port}")
    private  int port; //监听端口

    //连接map
    public  static Map<String, ChannelHandlerContext> map = new HashMap<String, ChannelHandlerContext>();


    @Override
    public void run(String... args) throws Exception {

        //创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(); //8个NioEventLoop

        try {
            ServerBootstrap b = new ServerBootstrap();
            /*将线程组传入*/
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)/*指定使用NIO进行网络传输*/
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程的连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            log.info("netty服务器启动成功 on port " + port);
            /*异步绑定到服务器，sync()会阻塞直到完成*/
            ChannelFuture channelFuture = b.bind(port).sync();
            //监听关闭 /*阻塞直到服务器的channel关闭*/
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            /**关闭线程组*/
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

}
